using UnityEngine;
using System;

public class SABattleCreatureMove
{
	public delegate void onMoveOverDelegate();


	public float acceleration = 0.0f;
	public float speed = GameDefine.DEFAULT_BATTLE_MOVE_SPEED;
	
	public float distance = 0.0f;
	public float sinX = 0.0f;
	public float cosX = 0.0f;
	
	public SABattlePos pos = new SABattlePos();
	public SABattlePos advancePos = new SABattlePos();
	public SABattlePos backPos = new SABattlePos();

	public SABattlePos movePos = new SABattlePos();
	public SABattlePos startPos = new SABattlePos();
	
	public SABattleCreature owner = null;
	private float time = 0.0f;
	
	public bool moving = false;
	
	public int moveDirection = (int)SAMapDirectionType.COUNT;
	public bool changeAction = true;

	public onMoveOverDelegate moveOverDelegate = null;

	public void endMoving()
	{
		if ( changeAction ) 
		{
			//owner.setAction( (int)SAActionType.STAND , 0 );
		}
		
		moving = false;
		
		pos.x = movePos.x;
		pos.y = movePos.y;
		
		startPos.x = movePos.x;
		startPos.y = movePos.y;

		owner.movePosReal();

		if ( moveOverDelegate != null ) 
		{
			moveOverDelegate();
		}
	}

	public void setMoveSpeed( float s )
	{
		speed = s;
	}

	public void startMove( float x , float y , float t , bool b = true )
	{
		moving = true;

		time = t;

		changeAction = b;
		
		movePos.x = x;
		movePos.y = y;

		distance = (float)Math.Sqrt( ( movePos.x - startPos.x ) * ( movePos.x - startPos.x ) + ( movePos.y - startPos.y ) * ( movePos.y - startPos.y ) );

		if ( distance == 0 )
		{
			Debug.LogError( "distance error" + distance );
			return;
		}

		sinX = ( movePos.y - startPos.y ) / distance;
		cosX = ( movePos.x - startPos.x ) / distance;

		if ( changeAction )
		{
			owner.setAction( (int)SAActionType.MOVE , owner.getDirection() );
		}
	}
	
	public void setPos( float x , float y )
	{
		startPos.x = x;
		startPos.y = y;
		
		pos.x = x;
		pos.y = y;
	}

	public void setAdvancePos( float x , float y )
	{
		advancePos.x = x;
		advancePos.y = y;
	}

	public void setBackPos( float x , float y )
	{
		backPos.x = x;
		backPos.y = y;
	}

	public void updateMove( float delay )
	{
		if ( !moving ) 
		{
			return;
		}
		
		time += delay;

		if ( time < 0.0f )
		{
			return;
		}

		float spd = speed + delay * acceleration * 0.001f;

		if ( spd < 0.1f ) 
		{
			spd = 0.1f;
		}
		
		float dis = time * spd;
		
		pos.x = cosX * dis + startPos.x;
		pos.y = sinX * dis + startPos.y;

		owner.movePosReal();

		if ( dis >= distance ) 
		{
			endMoving();
		}
	}
	
}

